<template>
  <div
    class="redenvelope-box"
    v-loading="loading"
    element-loading-background="rgba(0, 0, 0, 0.5)"
  >
    <div class="redenvelope-content">
      <div
        class="redenvelope animate__animated animate__flipInY"
        v-if="!showRule"
      >
        <div class="roll">
          <transition
            enter-active-class="animate__animated animate__fadeInUp"
            leave-active-class="animate__animated animate__fadeOutUp"
            @after-leave="onAfterLeave"
          >
            <p v-if="message.animated">
              {{ message?.time }} <span>{{ message?.user }}</span> 领取了<span
                class="coin"
                >{{ message?.coin }}</span
              >
              红包
            </p>
          </transition>
        </div>
        <div class="tips">加群 <span>724426197</span> 不定期发红包福利</div>
        <div class="form-item">
          <input
            class="input"
            type="text"
            autofocus
            v-model="password"
            placeholder="输口令 领红包"
          />
        </div>
        <div class="open" @click="onReceiveRedEnvelope">
          <img src="@/static/img/welfare/btn_open.png" />
        </div>
        <div class="list">
          <div class="item" v-for="item in redEnvelopeList" :key="item.id">
            <div class="left">
              <p>剩余数量</p>
              <span>{{(item.num - item.received_num) > (item.num / 2) ? '充足' : item.num - item.received_num}}</span>
            </div>
            <div class="right">
              <h3>{{item.title}}</h3>
              <!--<p>参与条件：01/01 00:00至01/01 00:00 充值超过50用户</p>
              <p>活动时间：2022/01/01 00:00:00至 2023/01/01 00:00:00</p>-->
              <p>{{item.descr}}</p>
              <p>{{$dayjs.unix(item.created_at).format('YYYY-MM-DD HH:mm:ss')}}</p>
            </div>
            <div class="btn">{{item.status == 1 ? '已结束' : '已开抢'}}</div>
          </div>
        </div>
        <div class="rule" @click="onSeeRule">口令红包规则</div>
      </div>
      <div v-else class="redenvelope-rule animate__animated animate__flipInY">
        <div class="title">口令红包规则</div>
        <div class="text">
          <p>
            1.输入红包口令，可获得随机硬币奖励，硬币用于平台内活动，不可直接兑换商城皮肤。
          </p>

          <p>
            2.同一台设备或网络环境最多可以从 1 个红包 中，获得 1 次奖励。
          </p>

          <p>
            3.口令可以通过官方QQ群、B站官方账号、活动等方式获得，口令和红包有时效性。
          </p>

          <p>
            红包最终解释权归本站所有，任何通过非法手段牟利都会导致资产冻结，或账号封禁。
          </p>
        </div>
        <div class="back" @click="showRule = false">返回红包封面</div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted, reactive, toRefs } from "vue";
import RedenvelopeService from "@/services/RedenvelopeService";
import { ElMessage } from "element-plus";
import { formatPassTime } from "@/utils";
import { useStore } from "@/store";

export default defineComponent({
  name: "Redenvelope",
  setup() {
    const store = useStore();
    const state = reactive({
      password: "",
      showRule: false,
      message: {
        time: "",
        user: "",
        coin: 0,
        animated: false,
      },
      loading: false,
      rollMessages: [],
      redEnvelopeList: []
    });

    let timer: number = 0;
    onMounted(async () => {
      await Promise.all([
        getRedEnvelopeList(),
        getRedEnvelopeRecord()
      ])
      timer = messageRoll();
    });

    onUnmounted(() => {
      clearInterval(timer);
    });

    function onAfterLeave() {
      state.message.animated = !state.message.animated;
    }

    function messageRoll() {
      return setInterval(() => {
        let message = state.rollMessages.pop();
        if (message) {
          state.message = {
            time: message.time,
            user: message.user,
            coin: message.coin,
            animated: !state.message.animated,
          };
          state.rollMessages.unshift(message);
        }
      }, 5000);
    }

    function onSeeRule() {
      state.showRule = true;
    }

    function getRedEnvelopeList() {
      return RedenvelopeService.getRedEnvelopeList({
        disabled: 0
      }).then(({data: { data: { list } }}) => {
        //console.log(list)
        state.redEnvelopeList = list
      })
    }

    function getRedEnvelopeRecord() {
      return RedenvelopeService.getRedEnvelopeRecord({
        page: 1,
        page_size: 20,
      }).then(({ data: { code, msg, data } }) => {
        if (data.list.length) {
          let messages = []
          data.list.forEach((item) => {
            messages.push({
              time: formatPassTime(item.receive_time * 1000),
              user: item.nickname,
              coin: item.money,
            });
          });
          state.rollMessages = messages
        }
      });
    }

    function onReceiveRedEnvelope() {
      if (state.loading) return;
      if (!state.password.length) {
        ElMessage.error("请输入红包口令");
        return;
      }
      state.loading = true;
      RedenvelopeService.receiveRedEnvelope({
        password: state.password,
      })
        .then(
          ({
            data: {
              data: { red_envelope_id, money },
            },
          }) => {
            ElMessage.success(`恭喜你成功领取 ${money} 硬币`);
            state.password = ''
            store.dispatch("getUserInfo");
            getRedEnvelopeRecord()
          }
        )
        .finally(() => {
          state.loading = false;
        });
    }

    return {
      ...toRefs(state),
      onSeeRule,
      onAfterLeave,
      onReceiveRedEnvelope,
    };
  },
});
</script>

<style lang="scss" scoped>
.redenvelope-box {
  width: 100%;
  height: 100%;
  background-image: url(@/static/img/welfare/bg_red_envelope.png);
  background-size: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-size: 14px;
  font-weight: 600;

  .redenvelope {
    width: 381px;
    height: 476px;
    background-image: url(@/static/img/welfare/bg_red_envelope_cover.png);
    background-size: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;

    .open {
      cursor: pointer;
      width: 76px;
      height: 76px;
      position: absolute;
      top: 170px;
      img {
        width: 100%;
      }
    }
    .open:hover {
      animation: heartBeat;
      animation-duration: 1s;
    }

    .roll {
      width: 324px;
      height: 30px;
      line-height: 30px;
      text-align: center;
      background: rgba(104, 3, 0, 0.3);
      border-radius: 15px;
      margin-top: 33px;
      span {
        color: #ffea00;
      }
      .coin::before {
        content: "";
        background-image: url(@/static/img/welfare/icon_coin.png);
        width: 12px;
        height: 12px;
        background-size: 100%;
        display: inline-block;
        margin: 0 5px;
        vertical-align: middle;
        margin-bottom: 3px;
      }
    }

    .tips {
      margin-top: 20px;
      span {
        color: #ffea00;
      }
    }

    .form-item {
      width: 258px;
      height: 42px;
      line-height: 42px;
      margin-top: 10px;
      .input {
        width: 100%;
        background: #fff7e1;
        border-radius: 10px;
        margin: 0;
        text-align: center;
        font-size: 16px;
        color: #ff8b00;
      }
      .input::placeholder {
        color: #d0a169;
      }
    }

    .list {
      width: 346px;
      height: 160px;
      overflow-y: auto;
      background-color: #c12311;
      border-radius: 10px;
      margin-top: 130px;
      padding-top: 10px;
      scroll-behavior: smooth;

      .item {
        padding: 10px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;

        .left {
          width: 80px;
          height: 90px;
          background-image: url(@/static/img/welfare/icon_red_envelope.png);
          position: relative;
          p {
            position: absolute;
            bottom: 24px;
            font-size: 12px;
            color: #ffc2b3;
            width: 100%;
            text-align: center;
          }
          span {
            position: absolute;
            bottom: 5px;
            font-size: 14px;
            font-weight: bold;
            text-align: center;
            width: 100%;
            color: #ffea00;
          }
        }

        .right {
          margin-left: 10px;
          flex: 1;
          font-size: 13px;
          line-height: 20px;
          color: #ffcac5;
        }

        .btn {
          margin-top: 10px;
          width: 100%;
          height: 35px;
          line-height: 35px;
          background: #df5858;
          border-radius: 20px;
          align-self: normal;
          text-align: center;
          color: #ffea00;
        }
      }
    }

    .rule {
      cursor: pointer;
      color: #ffcac5;
      font-size: 14px;
      text-decoration: underline;
      margin-top: 5px;
    }
  }

  .redenvelope-rule {
    width: 381px;
    height: 476px;
    background-image: url(@/static/img/welfare/bg_red_envelope_reverse.png);
    background-size: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #ffffff;
    position: relative;

    .title {
      margin-top: 50px;
      margin-bottom: 40px;
      font-size: 22px;
      font-weight: bold;
    }
    .text {
      font-size: 14px;
      padding: 10px 30px;
      p {
        margin-bottom: 20px;
      }
    }

    .back {
      position: absolute;
      bottom: 30px;
      font-size: 14px;
      text-decoration: underline;
      color: #ffcac5;
      cursor: pointer;
    }
  }
}

@media screen and (max-width: 768px) {
  .redenvelope-content {
    transform: scale(0.85);
    height: 100vh;
  }
  .redenvelope-box {
    background-position: bottom;
    .redenvelope {
      .rule {
        margin-top: 2px;
      }
    }
  }
}
</style>
